package com.hotel.api.controller;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hotel.api.common.Common;
import com.hotel.api.common.RedisOperator;
import com.hotel.api.entity.Lost;
import com.hotel.api.entity.Suggestion;
import com.hotel.api.entity.User;
import com.hotel.api.utils.JSONResult;
import com.hotel.api.service.*;
import com.hotel.api.utils.JsonUtils;
import com.hotel.api.utils.UploadFile;
import org.apache.commons.lang3.StringUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;

import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.spring.web.json.Json;

import java.text.SimpleDateFormat;
import java.util.*;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import static com.alibaba.druid.util.Utils.md5;

/**
 * 用户操作Controller
 *
 * @Author 涛涛
 * @Create 2019/8/29
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    RedisOperator redisOperator;

    //注入properties文件中存放文件的路径
    @Value("${web.upload-path}")
    private String path;


    @Autowired
    private AdminService adminService;

    @Autowired
    private UserService userService;

    @Autowired
    private RoomService roomService;

    /**
     * 添加信息
     *
     * @param suggestion
     * @return
     */
    @ApiOperation("用户添加意见")
    @PostMapping("/addSuggestion")
    public JSONResult addSuggestion(@RequestBody Suggestion suggestion) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = simpleDateFormat.format(new Date());
        suggestion.setState(1);
        suggestion.setCreateTime(date);
        int i = userService.addSuggestion(suggestion);
        if (i == 0) {
            return JSONResult.errorMsg("发表失败");
        }
        return JSONResult.ok("发表成功");
    }

    /**
     * 用户查看失物招领信息
     *
     * @return
     */
    @ApiOperation("用户查看失物招领信息")
    @GetMapping("/lostlist")
    public JSONResult showLostlist(@RequestParam(value = "page", defaultValue = "1", required = false) Integer page,
                                   @RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit) {
        PageHelper.startPage(page, limit);
        List<Lost> losts = adminService.selectAllLost();
        PageInfo<Lost> pageInfo = new PageInfo<>(losts);
        return JSONResult.ok(pageInfo);
    }

    /**
     * 根据uid查询个人意见信息
     *
     * @param uid
     * @return
     */
    @ApiOperation("根据uid查询个人意见信息")
    @GetMapping("/findByUid")
    public JSONResult findByUid(int uid) {
        List<Suggestion> suggestion = userService.findByUid(uid);
        if (suggestion.size() > 0) {
            return JSONResult.ok(suggestion);
        } else {
            return JSONResult.errorMsg("暂无个人意见信息");
        }
    }

    /**
     * 查询所有意见信息
     *
     * @return
     */
    @ApiOperation("查询所有意见信息")
    @PostMapping("/findAllSugs")
    public JSONResult findAllSugs(Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        List<Suggestion> suggestion = userService.findAll();
        PageInfo<Suggestion> pageInfo = new PageInfo<>(suggestion);
        if (suggestion.size() > 0) {
            return JSONResult.ok(pageInfo);
        } else {
            return JSONResult.errorMsg("暂无个人意见信息");
        }
    }


    /**
     * 工作人员更新意见信息即反馈处理
     *
     * @param suggestion
     * @return
     */
    @ApiOperation("管理员意见信息处理")
    @PostMapping("/updateSuggestion")
    public JSONResult updateSuggestion(Suggestion suggestion) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = simpleDateFormat.format(new Date());
        if (suggestion.getState() == 0) {
            suggestion.setFinishTime(date);
        }
        userService.updateSuggestion(suggestion);
        return JSONResult.ok("更新成功");

    }


    /**
     * 用户修改密码
     *
     * @param oldPassword
     * @param user
     * @return
     */
    @ApiOperation("用户修改密码")
    @PostMapping("/modifyPasswordByUserId")
    public JSONResult updatePassWord(String oldPassword, User user) {
        User user1 = userService.selectById(user.getId());
        //用户首次更改密码，初始密码状态下，不进行旧密码加密对比，因为数据库的密码就是123456
        if (user1.getPassword().equals("123456") && user1.getPassword().equals(oldPassword)) {
            userService.modifyPasswordByUserId(user);
            return JSONResult.build(200, "更改密码成功", null);
        }
        //数据库的密码此时是加密的，所以前端传过来的旧密码要进行加密再进行对比
        String password = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        if (!password.equals(user1.getPassword())) {
            return JSONResult.build(500, "旧密码错误", null);
        }
        userService.modifyPasswordByUserId(user);
        return JSONResult.build(200, "更改密码成功", null);

    }


    /**
     * 用户登录
     *
     * @param phoneNumber
     * @param password
     * @return
     */
    @PostMapping("/login")
    public JSONResult login(String phoneNumber, String password, HttpServletRequest httpServletRequest) {
        System.out.println("正常访问login");
        if (StringUtils.isBlank(phoneNumber)) {
            System.out.println("手机号不能为空");
            return JSONResult.errorMsg("手机号不能为空");
        }
        if (StringUtils.isBlank(password)) {
            System.out.println("密码不能为空");
            return JSONResult.errorMsg("密码不能为空");
        }
        User user = userService.selectByPhoneNumber(phoneNumber);

        if (user == null) {
            System.out.println("用户不存在");
            return JSONResult.errorMsg("用户不存在");
        }
        if (password.equals(user.getPassword())) {
            user.setPassword("******");
            System.out.println("登录成功");
            HttpSession httpSession = httpServletRequest.getSession();
            httpSession.setAttribute("UserInfo", JsonUtils.objectToJson(user));
            httpSession.setAttribute("loginUserId", user.getId());
//            redisOperator.set("loginUser:" + user.getId(), httpSession.getId());
            return JSONResult.build(200, "登录成功", user);
        }
        System.out.println("密码错误");
        return JSONResult.errorMsg("密码错误");


    }

    /**
     * 修改个人信息，当有图片时，可以上传该图片，把图片名称传入数据库
     *
     * @param user
     * @param file
     * @return
     */
    @ApiOperation("修改个人信息，当有图片时，可以上传该图片，把图片名称传入数据库")
    @PostMapping("/updateUserInfo")
    public JSONResult updateUserMsg(User user, MultipartFile file) {
        if (file != null) {
            String photoName = UploadFile.getFilePath(file);
            user.setHeadphoto(photoName);
        }
        int i = userService.update(user);
        if (i != 0) {
            return JSONResult.build(200, "修改个人信息成功", userService.selectById(user.getId()));
        } else {
            return JSONResult.errorMsg("修改失败");
        }
    }

    /**
     * 管理员修改用户信息
     *
     * @param user
     * @param file
     * @return
     */
    @ApiOperation("管理员修改用户信息")
    @PostMapping("/editUser")
    public JSONResult editUser(User user, @RequestParam(value = "file", required = false)
            MultipartFile file) {
        int i = 0;
        if (file != null) {
            String photoName = UploadFile.getFilePath(file);
            user.setHeadphoto(photoName);
        }
        if (user.getPassword() != null) {
            String password = user.getPassword();
            password = Common.MD5encode(password);
            user.setPassword(password);
        }

        i = userService.update(user);
        if (i >= 1) {
            return JSONResult.build(200, "用户信息修改成功", userService.selectById(user.getId()));
        } else {
            return JSONResult.errorMsg("修改失败");
        }
    }

    /**
     * 管理员添加用户信息
     *
     * @param user
     * @param file
     * @return
     */
    @ApiOperation("管理员添加用户信息")
    @PostMapping("/addUser")
    public JSONResult addUser(User user, @RequestParam(value = "file", required = false)
            MultipartFile file) {
        int i = 0;
        if (file != null) {
            String photoName = UploadFile.getFilePath(file);
            user.setHeadphoto(photoName);
        }

        if (user.getPassword() != null) {
            String password = user.getPassword();
            password = Common.MD5encode(password);
            user.setPassword(password);
        } else {
            user.setPassword("123456");
        }
        Integer roomNum = user.getRoomId();
        roomService.addRoomNumber(roomNum);
        i = userService.insert(user);

        if (i >= 1) {
            return JSONResult.build(200, "增加用户成功", userService.selectById(user.getId()));
        } else {
            return JSONResult.errorMsg("添加失败");
        }
    }


    /**
     * 管理员删除用户信息，假删，修改delState状态来表示
     *
     * @param id
     * @return
     */
    @ApiOperation("管理员删除用户信息，假删，修改delState状态来表示")
    @PostMapping("/deleteUser")
    public JSONResult deleteUser(Integer id) {
        System.out.println(id);
        int i = userService.deleteUser(id);
        if (i != 0) {
            return JSONResult.build(200, "删除用户成功！", i);
        } else {
            return JSONResult.errorMsg("删除失败，用户不存在");
        }
    }

    /**
     * 管理员查询所有用户
     *
     * @return
     */
    @ApiOperation("管理员查询所有用户")
    @PostMapping("/queryAllUser")
    public JSONResult queryAllUser(Integer page, Integer limit, Integer id) {
        if (id == null) {
            PageHelper.startPage(page, limit);
            List<User> userList = userService.selectAllUser();
            PageInfo<User> pageInfo = new PageInfo<>(userList);
            return JSONResult.build(200, "查询所有用户成功", pageInfo);
        } else {
            ArrayList<User> users = new ArrayList<User>();
            User user = userService.selectById(id);
            users.add(user);
            if (user != null) {
                return JSONResult.build(200, "查询id为" + id + "的用户成功", users);
            } else {
                return JSONResult.errorMsg("没有id为" + id + "的用户");
            }
        }
    }


    //管理员按照房间号查询该房间的人员情况
    @ApiOperation("管理员按照房间号查询该房间的人员情况")
    @GetMapping("/getUserbyRid")
    public JSONResult selectByRoomId(Integer rid) {
        List<User> users = userService.selectByRoomId(rid);
        if (users == null) {
            return JSONResult.build(200, "该房间为空", JSONResult.ok());
        } else {
            return JSONResult.build(200, "查询成功", users);
        }
    }

    /**
     * 用户退房，需要传入用户ID，退房时间，退房理由
     *
     * @param id
     * @param leaveTime
     * @param cause
     * @return
     */
    @ApiOperation("用户退房处理")
    @PostMapping("/leaveRoom")
    public JSONResult leaveRoom(Integer id, String leaveTime, String cause) {
        int leaveCount = userService.leaveRoom(id, leaveTime, cause);
        if (leaveCount != 0) {
            return JSONResult.build(200, "退房成功", leaveCount);
        } else {
            return JSONResult.errorMsg("退房失败，该用户不存在或已经退房");
        }
    }


    @ApiOperation("管理员根据用户姓名查询用户")
    @GetMapping("/queryByName")
    public JSONResult selectByName(String name) {
        User user = userService.selectByName(name);
        if (user != null) {
            return JSONResult.build(200, "查询用户成功", user);
        } else {
            return JSONResult.errorMsg("查询失败");
        }

    }

    @ApiOperation("管理员根据电话号码查询用户")
    @GetMapping("/queryByPhone")
    public JSONResult selectByPhone(String phone) {
        User user = userService.selectByPhoneNumber(phone);
        if (user != null) {
            return JSONResult.build(200, "查询用户成功", user);
        } else {
            return JSONResult.errorMsg("查询失败");
        }
    }

    @ApiOperation("管理员根据公司查询用户")
    @GetMapping("/queryByCompany")
    public JSONResult selectByCompany(String company) {
        User user = userService.selectByCompany(company);
        if (user != null) {
            return JSONResult.build(200, "查询用户成功", user);
        } else {
            return JSONResult.errorMsg("查询失败");
        }
    }

    @ApiOperation("管理员根据身份证查询用户")
    @GetMapping("/queryByIDCard")
    public JSONResult selectByIDCard(String idcard) {
        User user = userService.selectByIdcard(idcard);
        if (user != null) {
            return JSONResult.build(200, "查询用户成功", user);
        } else {
            return JSONResult.errorMsg("查询失败");
        }
    }

    @ApiOperation("根据ID查询用户")
    @PostMapping("/queryByID")
    public JSONResult selectByID(Integer id) {
        User user = userService.selectById(id);
        if (user != null) {
            return JSONResult.build(200, "查询用户成功", user);
        } else {
            return JSONResult.errorMsg("查询失败");
        }

    }
}
